package com.qiantu.phone.ui.activity;

import static com.qiantu.api.entity.RoomBean.COMMON_ROOM_ID;
import static com.qiantu.api.entity.RoomBean.ROOM_COMMON_SERIALNO;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.hjq.base.BaseActivity;
import com.hjq.http.listener.HttpCallback;
import com.qiantu.api.db.LLDeviceDBManager;
import com.qiantu.api.db.LLDeviceGroupDBManager;
import com.qiantu.api.db.LLFloorDBManager;
import com.qiantu.api.db.LLRoomDBManager;
import com.qiantu.api.entity.DeviceBean;
import com.qiantu.api.entity.DeviceBindGroupBean;
import com.qiantu.api.entity.FloorBean;
import com.qiantu.api.entity.QueryCodeResultBean;
import com.qiantu.api.entity.RoomBean;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.R;
import com.qiantu.phone.aop.SingleClick;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.event.GroupAddEvent;
import com.qiantu.phone.event.RefreshDeviceListEvent;
import com.qiantu.phone.ui.dialog.BottomAddDeviceEditDialog;
import com.qiantu.phone.ui.fragment.SmartAppliancesFragment;
import com.lxj.xpopup.XPopup;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

public class GroupDeviceListActivity  extends AppActivity {
    public static void start(Context context, String deviceSerialNo, String controllerSerialNo,int activityType) {
        start(context,deviceSerialNo,controllerSerialNo,"","",activityType);
    }

    public static void start(Context context, String deviceSerialNo, String controllerSerialNo,String targetSerialNo,String title,int activityType){
        Intent intent = new Intent(context, GroupDeviceListActivity.class);
        intent.putExtra("deviceSerialNo", deviceSerialNo);
        intent.putExtra("controllerSerialNo", controllerSerialNo);
        intent.putExtra("activityType", activityType);
        intent.putExtra("targetSerialNo", targetSerialNo);
        intent.putExtra("title", title);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    private TextView removeBtn;

    private SmartAppliancesFragment mSmartAppliancesFragment;

    private BottomAddDeviceEditDialog mBottomAddDeviceEditDialog;

    private DeviceBean deviceBean;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_group_device_list;
    }

    @Override
    protected void initView() {
        int activityType = getIntent().getIntExtra("activityType",1);
        String titleStr= getIntent().getStringExtra("title");
        if(!titleStr.equals("")){
            getTitleBar().getTitleView().setText(titleStr);
        }
        removeBtn = findViewById(R.id.btn_removeFromGroup);
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        setOnClickListener(R.id.btn_removeFromGroup);
        if(activityType == 1){
            String controllerSerialNo = getIntent().getStringExtra("controllerSerialNo");
            getTitleBar().setRightTitle(R.string.devicegroup_setting_edit);
            removeBtn.setVisibility(View.GONE);
            mSmartAppliancesFragment = SmartAppliancesFragment.newInstance(SmartAppliancesFragment.SearchType.SEARCH_TYPE_GROUP_DEVICE,controllerSerialNo);
            mSmartAppliancesFragment.setSelectable(true);
        }else{
            String deviceSerialNo = getIntent().getStringExtra("deviceSerialNo");
            getTitleBar().setRightTitle("");
            removeBtn.setVisibility(View.VISIBLE);
            mSmartAppliancesFragment = SmartAppliancesFragment.newInstance(SmartAppliancesFragment.SearchType.SEARCH_TYPE_GROUP_CONTAIN_DEVICE,deviceSerialNo);
            mSmartAppliancesFragment.setSelectable(false);
        }
        mSmartAppliancesFragment.setSingleSelect(false);
        fragmentTransaction.add(R.id.fragment, mSmartAppliancesFragment);
        fragmentTransaction.commitNowAllowingStateLoss();
    }

    @Override
    protected void initData() {
        int activityType = getIntent().getIntExtra("activityType",1);
        if(activityType == 1){
            deviceBean = new DeviceBean();
            deviceBean.setDeviceType("tctdl");
            deviceBean.setType("light");
            deviceBean.setName("");
            deviceBean.setLinkType(2);
            deviceBean.setRoomSerialNo("");
            deviceBean.setImageUrl("icon_device_light");
            deviceBean.setHouseSerialNo(AppApplication.getInstance().getCurrentHouseSerialNo());

            String deviceSerialNo = getIntent().getStringExtra("deviceSerialNo");
            List<String> list = new ArrayList<>();
            list.add(deviceSerialNo);
            List<DeviceBindGroupBean> deviceBindGroupBeanList = LLDeviceGroupDBManager.getInstance(getContext()).getDeviceGroupsByDeviceGroupSerialNo(list);
            List<String> serialNos = new ArrayList<>();
            for(int i = 0;i < deviceBindGroupBeanList.size();i++){
                serialNos.add(deviceBindGroupBeanList.get(i).getDeviceSerialNo());
            }
            List<DeviceBean> selectedDevices = LLDeviceDBManager.getInstance(getContext()).getDevicesByDeviceSerialNos(serialNos);
            if(selectedDevices != null && selectedDevices.size() > 0){
                mSmartAppliancesFragment.checkSelected(selectedDevices);
                getTitleBar().getRightView().setEnabled(true);
            }else{
                getTitleBar().getRightView().setEnabled(false);
            }
        }else{

        }

    }

    public void onSelectedDevices(ArrayList<DeviceBean> selectedDevices){
        if(selectedDevices == null || selectedDevices.size() == 0){
            getTitleBar().getRightView().setEnabled(false);
        }else{
            getTitleBar().getRightView().setEnabled(true);
        }
    }

    @Override
    public void onRightClick(View view) {
        List<DeviceBean> deviceBeans = mSmartAppliancesFragment.getSelectedDevices();
        List<Map> deviceSerialNos = new ArrayList<>();
        for(int i = 0;i < deviceBeans.size();i++){
            Map<String,String> map = new HashMap<>();
            map.put("deviceSerialNo",deviceBeans.get(i).getDeviceSerialNo());
            deviceSerialNos.add(map);
        }
        String deviceSerialNo = getIntent().getStringExtra("deviceSerialNo");
        if(deviceSerialNo.equals("")){
            showBottomAddDeviceEditDialog(deviceSerialNos);
        }else{
            LLHttpManager.saveGroupDevice(this,deviceSerialNo,deviceSerialNos,new HttpCallback<HttpData<QueryCodeResultBean<String, DeviceBean>>>(this){

                @Override
                public void onStart(Call call) {
                    showDialog();
                }

                @Override
                public void onSucceed(HttpData<QueryCodeResultBean<String, DeviceBean>> result){
                    toast(R.string.reset_success);
                    QueryCodeResultBean resultBean = result.getData();
                    DeviceBean deviceBean = (DeviceBean) resultBean.getRspData();
                    List<DeviceBindGroupBean> deviceBindGroupBeans = deviceBean.getDeviceBindGroups();
                    LLDeviceGroupDBManager.getInstance(getContext()).removeByGroupSerialNo(deviceSerialNo);
                    LLDeviceGroupDBManager.getInstance(getContext()).addBatch(deviceBindGroupBeans);
                    EventBus.getDefault().post(new GroupAddEvent());
                    finish();
                }

                @Override
                public void onFail(Exception e) {
                    super.onFail(e);
                }

                @Override
                public void onEnd(Call call) {
                    hideDialog();
                }
            });
        }
    }

    private void showBottomAddDeviceEditDialog(List<Map> deviceSerialNos) {
        if (mBottomAddDeviceEditDialog == null) {
            mBottomAddDeviceEditDialog = new BottomAddDeviceEditDialog(this);
            mBottomAddDeviceEditDialog.setDialogClickListener(new BottomAddDeviceEditDialog.DialogClickListener() {
                @Override
                public void onDeviceIconClick() {
                    Intent intent = new Intent(getContext(), DeviceIconSelectActivity.class);
                    intent.putExtra("type", deviceBean.getType());
                    intent.putExtra("deviceType", deviceBean.getDeviceType());
                    intent.putExtra("selectIcon", deviceBean.getImageUrl());
                    startActivityForResult(intent, new BaseActivity.OnActivityCallback() {
                        @Override
                        public void onActivityResult(int resultCode, Intent data) {
                            if (resultCode == RESULT_OK) {
                                String selectIconUrl = data.getStringExtra("DATA");
                                deviceBean.setImageUrl(selectIconUrl);
                                mBottomAddDeviceEditDialog.setDeviceIcon(deviceBean.getOnImageUrl());
                            }
                        }
                    });
                }

                @Override
                public void onDeviceFloorRoomClick() {
                    Intent intent = new Intent(getContext(), SelectFloorRoomActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    startActivityForResult(intent, new BaseActivity.OnActivityCallback() {
                        @Override
                        public void onActivityResult(int resultCode, Intent data) {
                            if (resultCode == RESULT_OK){
                                String serialNo = data.getStringExtra("serialNo");
                                String roomName = data.getStringExtra("roomName");
                                String floorSerialNo = data.getStringExtra("floorSerialNo");
                                String floorName = data.getStringExtra("floorName");
                                deviceBean.setFloorSerialNo(serialNo);
                                deviceBean.setFloorName(floorName);
                                if(serialNo.equals(floorSerialNo)){
                                    deviceBean.setLinkType(3);
                                    deviceBean.setRoomSerialNo(RoomBean.ROOM_COMMON_SERIALNO);
                                    deviceBean.setRoomName("");
                                    mBottomAddDeviceEditDialog.setFloorRoom(deviceBean.getFloorName());
                                }else{
                                    deviceBean.setRoomSerialNo(serialNo);
                                    if (ROOM_COMMON_SERIALNO.equals(serialNo)){
                                        deviceBean.setLinkType(2);
                                    }else {
                                        deviceBean.setLinkType(1);
                                    }
                                    deviceBean.setRoomName(roomName);
                                    mBottomAddDeviceEditDialog.setFloorRoom(TextUtils.isEmpty(deviceBean.getFloorName()) ? roomName : deviceBean.getFloorName() + roomName);
                                }
                            }
                        }
                    });
                }

                @Override
                public void onConfirmClick() {
                    String name = mBottomAddDeviceEditDialog.getText();
                    if(TextUtils.isEmpty(name)){
                        toast(R.string.device_name);
                        return;
                    }
                    deviceBean.setName(name);
                    saveGroup(deviceSerialNos);
                    mBottomAddDeviceEditDialog.dismiss();
                }
            });
            new XPopup.Builder(this)
                    .dismissOnBackPressed(true)
                    .enableDrag(true)
                    .asCustom(mBottomAddDeviceEditDialog);
        }
        mBottomAddDeviceEditDialog.setDeviceName(deviceBean.getName());
        mBottomAddDeviceEditDialog.setDeviceIcon(deviceBean.getOnImageUrl());
        mBottomAddDeviceEditDialog.setFloorRoom(LLRoomDBManager.getInstance(getContext()).getFloorRoomName(deviceBean.getRoomSerialNo()));
        mBottomAddDeviceEditDialog.setEditType(2);
        mBottomAddDeviceEditDialog.show();
    }

    public void saveGroup(List<Map> deviceSerialNos){
        LLHttpManager.addGroupDevice(this,deviceBean,deviceSerialNos,new HttpCallback<HttpData<QueryCodeResultBean<String, DeviceBean>>>(this){

            @Override
            public void onStart(Call call) {
                showDialog();
            }

            @Override
            public void onSucceed(HttpData<QueryCodeResultBean<String, DeviceBean>> result){
                toast(R.string.reset_success);
                QueryCodeResultBean resultBean = result.getData();
                DeviceBean deviceBean = (DeviceBean) resultBean.getRspData();
                deviceBean.setDeviceGroup(1);
                deviceBean.setDeviceSerialNo(deviceBean.getDeviceGroupSerialNo());
                List<DeviceBean> deviceBeanList = new ArrayList<>();
                deviceBeanList.add(deviceBean);
                LLDeviceDBManager.getInstance(getContext()).addBatch(deviceBeanList);
                List<DeviceBindGroupBean> deviceBindGroupBeans = deviceBean.getDeviceBindGroups();
                LLDeviceGroupDBManager.getInstance(getContext()).addBatch(deviceBindGroupBeans);

                EventBus.getDefault().post(new RefreshDeviceListEvent());
                finish();
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);
            }

            @Override
            public void onEnd(Call call) {
                hideDialog();
            }
        });
    }

    public void groupRemoveDevice(){
        String deviceGroupSerialNo = getIntent().getStringExtra("deviceSerialNo");
        String deviceSerialNo = getIntent().getStringExtra("targetSerialNo");
        LLHttpManager.groupRemoveDevice(this,deviceGroupSerialNo,deviceSerialNo,new HttpCallback<HttpData<Void>>(this){
            @Override
            public void onStart(Call call) {
                showDialog();
            }

            @Override
            public void onSucceed(HttpData<Void> result){
                toast(R.string.reset_success);
                LLDeviceGroupDBManager.getInstance(getContext()).removeDeviceInGroup(deviceGroupSerialNo,deviceSerialNo);
                EventBus.getDefault().post(new RefreshDeviceListEvent());
                finish();
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);
            }

            @Override
            public void onEnd(Call call) {
                hideDialog();
            }
        });
    }

    @SingleClick
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_removeFromGroup:
                groupRemoveDevice();
                break;
        }
    }
}
